let express = require("express");
let uunewid = require("uuid");
let router = express.Router();
var constants = require("../utils/constants");
const { checkAuth } = require("../utils/utils");
const { ohana } = require("ohana-node-orm");
const ohana_instance = new ohana("SAP_JIANGDU_TALENTS");
let log = require("cf-nodejs-logging-support");
log.setLoggingLevel("info");

router.post("/", async (req, res, next) => {
  // #swagger.tags = ['需求']
  // #swagger.summary = '创建需求'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /*	#swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                        $ref: "#/definitions/request"
                    }  
                },
            }
    } */
  const user = checkAuth(req.user, constants.BASICAUTH);

  if (!user.authCheck) {
    res.sendStatus(403);
  }

  const { data } = req.body;

  data.uuid = uunewid.v4();
  data.USER_ID = user.user_id;

  const result = await insertJsonDoc(data);
  if (result == 1) {
    res.sendStatus(200);
  } else {
    res.sendStatus(500);
  }
});

router.get("/", async (req, res, next) => {
  // #swagger.tags = ['需求']
  // #swagger.summary = '获取需求'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  const user = checkAuth(req.user, constants.BASICAUTH);

  if (!user.authCheck) {
    res.sendStatus(403);
  }
  let { type } = req.query;
  const result = await getJsonDoc(user.user_id, type);
  res.send(result);
});

router.get("/single", async (req, res, next) => {
  // #swagger.tags = ['需求']
  // #swagger.summary = '获取需求'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  const user = checkAuth(req.user, constants.BASICAUTH);

  if (!user.authCheck) {
    res.sendStatus(403);
  }
  let { UUID } = req.query;
  const result = await getSingleJsonDoc(UUID);
  res.send(result);
});

router.put("/", async (req, res, next) => {
  // #swagger.tags = ['需求']
  // #swagger.summary = '更新需求'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /*	#swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                        $ref: "#/definitions/request_update"
                    }  
                },
            }
    } */
  const { data } = req.body;
  const result = await updateJsonDoc(data);
  if (result == 1) {
    res.sendStatus(200);
  } else {
    res.sendStatus(500);
  }
});

router.delete("/", async (req, res, next) => {
  // #swagger.tags = ['需求']
  // #swagger.summary = '删除需求'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /*	#swagger.requestBody = {
          required: true,
          content: {
              "application/json": {
                  schema: {
                      $ref: "#/definitions/request_delete"
                  }  
              },
          }
  } */
  const { data } = req.body;
  const result = await deleteJsonDoc(data);

  if (result == 1) {
    res.sendStatus(200);
  } else {
    res.sendStatus(500);
  }
});

async function insertJsonDoc(data) {
  var json = JSON.stringify(data); // {"type":"Fiat","model":"500","color":"White"}为了去掉"符合HANA json 插入的格式
  log.info(json);
  var unquoted = json.replace(/"([^"]+)":/g, "$1:");
  log.info(unquoted);
  let resultText = unquoted.replace(new RegExp('"', "g"), "'");
  log.info(resultText);
  var stringText = "insert into REQUEST_COLLECTION values(" + resultText + ")";
  const result = await ohana_instance.raw(stringText);
  return result;
}
async function getJsonDoc(userId, type) {
  const ohana_instance = new ohana("SAP_JIANGDU_FREQUENTLY_USED_ENTERPRISES");
  var stringText =
    "select * from  REQUEST_COLLECTION where USER_ID = '" +
    userId +
    "' and TYPE = '" +
    type +
    "'";
  const result = await ohana_instance.raw(stringText);
  let parsedResult = [];
  result.forEach((element) => {
    parsedResult.push(JSON.parse(element.REQUEST_COLLECTION));
  });
  return parsedResult;
}

async function getSingleJsonDoc(UUID) {
  const ohana_instance = new ohana("SAP_JIANGDU_FREQUENTLY_USED_ENTERPRISES");
  var stringText =
    "select * from  REQUEST_COLLECTION where UUID = '" + UUID + "'";
  const result = await ohana_instance.raw(stringText);
  let parsedResult = [];
  result.forEach((element) => {
    parsedResult.push(JSON.parse(element.REQUEST_COLLECTION));
  });
  return parsedResult[0];
}

async function updateJsonDoc(data) {
  const ohana_instance = new ohana("SAP_JIANGDU_FREQUENTLY_USED_ENTERPRISES");
  var json = JSON.stringify(data.DATA); // {"type":"Fiat","model":"500","color":"White"}为了去掉"符合HANA json 插入的格式
  var unquoted = json.replace(/"([^"]+)":/g, "$1:");
  let resultText = unquoted.replace(new RegExp('"', "g"), "'");
  var stringText =
    "update REQUEST_COLLECTION SET DATA = " +
    resultText +
    " where UUID = '" +
    data.UUID +
    "'";
  const result = await ohana_instance.raw(stringText);
  return result;
}

async function deleteJsonDoc(data) {
  const ohana_instance = new ohana("SAP_JIANGDU_FREQUENTLY_USED_ENTERPRISES");
  var stringText =
    "delete from  REQUEST_COLLECTION where UUID = '" + data.UUID + "'";
  const result = await ohana_instance.raw(stringText);
  return result;
}

module.exports = router;
